const request = require("request");
const config = require("./config");
module.exports = class Request {
    constructor() {
        // 请求默认配置
        this.requestConfig = {
            header: {
                "X-Requested-With": "XMLHttpRequest",
            },
            method: "GET",
            dataType: "json",
            responseType: "text",
        };
        //拦截器
        this.interceptors = {
            request: (fun) => {
                if (fun) {
                    Request.requestBefore = fun;
                } else {
                    Request.requestBefore = (request) => request;
                }
            },
            response: (fun) => {
                if (fun) {
                    Request.requestAfter = fun;
                } else {
                    Request.requestAfter = (response) => {
                        response;
                    };
                }
            },
        };
    }

    static requestBefore(config) {
        return config;
    }

    static requestAfter(response) {
        return response;
    }

    static isCompleteURL(url) {
        return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
    }

    request(options = {}) {
        options.method = options.method || this.requestConfig.method;
        options.header = options.header || this.requestConfig.header;
        options = {...options, ...Request.requestBefore(options)};
        //不是http开头
        if (!Request.isCompleteURL(options.url)) {
            options.url = `${config.baseUrl}/${options.url}`;
        }
        return new Promise((resolve, reject) => {
            request(options, (error, response, body) => {
                resolve(Request.requestAfter(error, response, body, options));
            });
        });
    }

    get(options = {}) {
        options.method = "GET";
        return this.request(options);
    }

    post(options = {}) {
        options.method = "POST";
        return this.request(options);
    }

    put(options = {}) {
        options.method = "PUT";
        return this.request(options);
    }

    del(options = {}) {
        options.method = "DELETE";
        return this.request(options);
    }
};
